// by Xeno
//#define __DEBUG__
#define THIS_FILE "x_helirespawn2.sqf"
#include "x_setup.sqf"
private ["_heli_array", "_vec_a", "_vehicle", "_number_v", "_is_blufor_chopper", "_i", "_tt", "_ifdamage", "_empty", "_disabled", "_empty_respawn", "_startpos", "_hasbox", "_fuelleft","_reserved","_vec_varname"];
if (!isServer) exitWith{};

_heli_array = [];
{
	_vec_a = _x;
	_vehicle = _vec_a select 0;
	if (!isNil "_vehicle" && {!isNull _vehicle}) then {
		_number_v = _vec_a select 1;
		_ifdamage = _vec_a select 2;
		// TYRGHEN ADDITION
		_reserved = false;
		if (count _vec_a > 4) then { _reserved = _vec_a select 4 };
		_disabled_time = 0;
		//TYRGHEN - added disabled time to control spawn timing
		if (count _vec_a > 5) then { _disabled_time = _vec_a select 5 };
		_vec_varname = vehicleVarName _vehicle;
		_vehicle setVariable [QGVAR(DISABLED_TIMEOUT), -1];

		//TYRGHEN - Check for double vehicles on the same spot
		_vecs = nearestObjects [_vehicle, [typeOf _vehicle], 1];
		if (count _vecs > 1) then {
			diag_log format["Multiple Vehicles at initialization: %1, %2",_vec_varname,_vecs];
			{
				if (_x != _vehicle) then { deleteVehicle _x; }
			} foreach _vecs;
		};

		_vposp = position _vehicle;
		_vposp set [2, (_vposp select 2) + 0.1];
		_arr = [_vehicle, _number_v, _ifdamage, -1, _vposp, direction _vehicle, typeOf _vehicle, if (_ifdamage) then {-1} else {_vec_a select 3},_reserved,_vec_varname,_disabled_time];
		__TRACE_1("","_arr");
		_heli_array set [count _heli_array, _arr];
		
		_vehicle setVariable [QGVAR(OUT_OF_SPACE), -1];
		_vehicle setVariable [QGVAR(vec), _number_v, true];
		_vehicle setVariable [QGVAR(vec_islocked), (_vehicle call FUNC(isVecLocked))];
		// TYRGHEN ADDITION
		_vehicle setVariable [QGVAR(team_reserved),_reserved,true];
		if (_reserved) then {
			_vehicle addEventHandler ["Engine", {_this spawn {sleep 3; if (isnull (driver (_this select 0)) && isEngineOn(_this select 0)) then { (_this select 0) engineOn false; (_this select 0) setFuel 0; sleep 1; (_this select 0) setFuel 1; };}}];
		};
		_vehicle addEventHandler ["GetIn", {if (!isplayer (_this select 2) && !isplayer(leader (_this select 2))) then { (_this select 2) action ["eject",(_this select 0)]; }; }];
		
		_vehicle setPos _vposp;
		_vehicle setDamage 0;
		
		// TYRGHEN
		_vehicle addItemCargoGlobal ["ToolKit", 2];

#ifdef __TT__
		if (_number_v < 4000) then {
			_vehicle addMPEventhandler ["MPKilled", {if (isServer) then {_this call FUNC(checkveckillblufor)}}];
		} else {
			_vehicle addMPEventhandler ["MPKilled", {if (isServer) then {_this call FUNC(checkveckillopfor)}}];
		};
#endif
	};
} forEach _this;
_this = nil;

sleep 10;

_isfirst = true;
#ifdef __DEBUG__
GVAR(HeliRespawnArray) = _heli_array;
#endif
while {true} do {
	call FUNC(mpcheck);
	{
		_tt = 20 + random 10;
		sleep _tt;
		_vec_a = _x;
		_vehicle = _vec_a select 0;
		_ifdamage = _vec_a select 2;
		
		_empty = _vehicle call FUNC(GetVehicleEmpty);
		
		_disabled = false;
		if (!_ifdamage) then {
			if (_empty) then {
				_empty_respawn = _vec_a select 3;
				if (_empty_respawn == -1) then {
					if (_vehicle distance (_vec_a select 4) > 10) then {
						_vec_a set [3, time + (_vec_a select 7)];
					};
				} else {
					if (time > _empty_respawn && {{_x distance _vehicle < 100} count (if (isMultiplayer) then {playableUnits} else {switchableUnits}) == 0}) then {
						_disabled = true;
					};
				};
			} else {
				if (alive _vehicle) then {_vec_a set [3,-1]};
			};
		};
			
		if (!_disabled && {damage _vehicle >= 0.9}) then {_disabled = true};
		
		if (_empty && {!_disabled} && {alive _vehicle} && {(_vehicle call FUNC(OutOfBounds))}) then {
			_outb = GV(_vehicle,GVAR(OUT_OF_SPACE));
			if (_outb != -1) then {
				if (time > _outb) then {_disabled = true};
			} else {
				_vehicle setVariable [QGVAR(OUT_OF_SPACE), time + 600];
			};
		} else {
			_vehicle setVariable [QGVAR(OUT_OF_SPACE), -1];
		};
		
		sleep 0.01;
		// TYRGHEN - moved check out of the main function to avoid the object from being cleaned up
		//           now the helicopter remains there until the disabled timeout is reached
		_disabled_timeout = 0;
		if (_disabled) then {
			_hasbox = GV(_vehicle,GVAR(ammobox));
			if (!isNil "_hasbox" && {_hasbox}) then {[QGVAR(num_ammo_boxes),__XJIPGetVar(GVAR(num_ammo_boxes)) - 1] call FUNC(NetSetJIP)};
			//TYRGHEN - added disabled time to control spawn timing, only if the vehicle has been destroyed
			if (!alive _vehicle) then {
				_disabled_timeout = _vehicle getVariable [QGVAR(DISABLED_TIMEOUT), -1];
				_disabled_time = _vec_a select 10;
				if (_disabled_timeout <= 0 && _disabled_time > 0) then {
					_disabled_timeout = time + _disabled_time;
					_vehicle setVariable [QGVAR(DISABLED_TIMEOUT), _disabled_timeout];
				};
			};
		};
	
		// TYRGHEN
		//if ((_disabled && {_empty}) || {(_empty && {!alive _vehicle})}) then {
		#ifdef __DEBUG__
			if (damage _vehicle > 0.5) then {
				_var_test = [_vehicle,_disabled,_disabled_timeout,time,_empty,!alive _vehicle];
				__TRACE_1("_var_test","_var_test");
			};
		#endif
		if ((_disabled && (_disabled_timeout <= time) && {_empty}) || {(_empty && (_disabled_timeout <= time) && {!alive _vehicle})}) then {
			// TYRGHEN
			// Reset the timeout to allow the next timeout.
			_disabled_timeout = 0;
			_hasbox = GV(_vehicle,GVAR(ammobox));
			_fuelleft = GV(_vehicle,GVAR(fuel));
			if (isNil "_fuelleft") then {_fuelleft = 1};
			//TYRGHEN
			if (_fuelleft <= 0.3) then { _fuelleft = 1};
			// TYRGHEN - Done above
			// if (!isNil "_hasbox" && {_hasbox}) then {[QGVAR(num_ammo_boxes),__XJIPGetVar(GVAR(num_ammo_boxes)) - 1] call FUNC(NetSetJIP)};
			_isitlocked = GV(_vehicle,GVAR(vec_islocked)) || {_vehicle call FUNC(isVecLocked)};
			// TYRGHEN
			if (isnil "_isitlocked") then { _isitlocked = false };
			sleep 0.1;
			deletevehicle _vehicle;
			if (!_ifdamage) then {_vec_a set [3,-1]};
			sleep 0.5;
			// TYRGHEN - emptying the spot of respawn
			_objs = nearestObjects [_vec_a select 4, ["CAManBase","AllVehicles"], 10];
			__TRACE_1("","_objs")
			{
				_new_pos = (_vec_a select 4) findEmptyPosition[ 12 , 50, typeof _x];
				if (count _new_pos > 0) then { _x setPos _new_pos; sleep 1; };
			} foreach _objs;
			
			_vehicle = objNull;
			_vehicle = createVehicle [_vec_a select 6, _vec_a select 4, [], 0, "NONE"];
			_vehicle setdir (_vec_a select 5);
			_vehicle setpos (_vec_a select 4);
			
			_vehicle setVariable [QGVAR(vec_islocked), _isitlocked];
			if (_isitlocked) then {_vehicle lock true};
			
			_vehicle setFuel _fuelleft;
			_vehicle setDamage 0;
			
			// TYRGHEN - in cases of spawning over debris
			_vehicle allowDamage false;
			_vehicle spawn { sleep 10; _this allowDamage true; };
			_vec_varname = (_vec_a select 9);
			_vehicle setVehicleVarName _vec_varname;
			_vehicle setVariable [QGVAR(vec_varname),_vec_varname,true];
			_vehicle call compile format ["%1=_vehicle;",_vec_varname];
			_vehicle setVariable [QGVAR(DISABLED_TIMEOUT), -1];
			
			// TYRGHEN ADDITION
			_reserved = _vec_a select 8;
			_vehicle setVariable [QGVAR(team_reserved),_reserved,true];
			if (_reserved) then {
				_vehicle addEventHandler ["Engine", {_this spawn {sleep 3; if (isnull (driver (_this select 0)) && isEngineOn(_this select 0)) then { (_this select 0) engineOn false; (_this select 0) setFuel 0; sleep 1; (_this select 0) setFuel 1; };}}];
			};
			_vehicle addEventHandler ["GetIn", {if (!isplayer (_this select 2) && !isplayer(leader (_this select 2))) then { (_this select 2) action ["eject",(_this select 0)]; }; }];

			// TYRGHEN
			_vehicle addItemCargoGlobal ["ToolKit", 2];
			
			_vec_a set [0,_vehicle];
			_heli_array set [_forEachIndex, _vec_a];
			_number_v = _vec_a select 1;
			_vehicle setVariable [QGVAR(OUT_OF_SPACE), -1];
			_vehicle setVariable [QGVAR(vec), _number_v, true];
			[QGVAR(n_v), _vehicle] call FUNC(NetCallEventToClients);
			_vehicle addMPEventhandler ["MPKilled", {if (isServer) then {_this call FUNC(fuelCheck)}}];
			
#ifdef __TT__
			if (_number_v < 4000) then {
				_vehicle addMPEventhandler ["MPKilled", {if (isServer) then {_this call FUNC(checkveckillblufor)}}];
			} else {
				_vehicle addMPEventhandler ["MPKilled", {if (isServer) then {_this call FUNC(checkveckillopfor)}}];
			};
#endif
		};
	} forEach _heli_array;
	sleep 20 + random 5;
};